<template>
    <teleport to="#BreadcrumbTeleportRight">
        <el-button type="primary" @click="showHighLevel">会员等级高级设置</el-button>
    </teleport>

    <el-table
        border-t
        v-loading="tableLoading"
        :data="tableData"
        :empty-text="emptyText"
        class="table-loading-mask-body"
    >
        <el-table-column label="会员等级" min-width="100" show-overflow-tooltip>
            <template #default="{ row }">{{ row.level || '--' }}</template>
        </el-table-column>
        <el-table-column label="等级名称" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">{{ row.name || '--' }}</template>
        </el-table-column>
        <el-table-column label="有效期" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">{{ row.effectiveDays }}</template>
        </el-table-column>
        <el-table-column label="升级至本等级条件" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">{{ row.upgradeConditions || '--' }}</template>
        </el-table-column>
        <el-table-column label="保级条件" min-width="180" show-overflow-tooltip>
            <template #default="{ row }">{{ row.qualificationCriteria || '--' }}</template>
        </el-table-column>
        <el-table-column label="会员卡卡面" min-width="120">
            <template #default="{ row }">
                <el-image :src="row.card_img_url" style="height: 35px;"/>
            </template>
        </el-table-column>
        <el-table-column fixed="right" width="150">
            <template #header><span class="pl3">操作</span></template>
            <template #default="{ row, $index }">
                <el-button v-if="isEdit" link type="primary" @click="editLevel(row,$index)">编辑</el-button>
                <el-button v-if="isEdit && row.showDelete" link type="danger" @click="removeLevels($index)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <div v-if="isEdit">
        <div class="pa20">
            <el-text type="primary" class="mr12 pointer" @click="addOrdinaryLevel">+添加{{ noSpecialLevelsIndex >= 0 ? '下一' : '' }}普通等级</el-text>
            <el-text type="primary" class="mr12 pointer" @click="addSpecialLevel">+添加特殊等级</el-text>
            <el-text>*特殊等级不参与自动升降级哦</el-text>
        </div>
        <div class="pa20 border-t">
            <el-button type="primary" size="default" class="fz13 w120" @click="onLevelUpdate">提交并更新</el-button>
            <el-button type="info" size="default" class="fz13 w120" @click="closeEdit">取消</el-button>
        </div>
    </div>
    <div v-else-if="showPageBtn" class="pa20 f-c">
        <el-button type="primary" size="default" class="fz13 w120 mr20" @click="onEdit">编辑</el-button>
        <div v-if="isUpdate">
            <span class="fz12">当前为待更新版本(凌晨2点更新)，查看</span>
            <el-text type="primary" class="ml5 pointer" @click="routerLevelUpdate">线上正在使用的版本 ></el-text>
        </div>
    </div>

    <AddLevel v-model="addLevelDialog" :detail="memberDetail" :is-special="isSpecial" @change="addLevelValue"/>

    <HighLevel v-model="highLevelDialog"/>
</template>

<script setup lang="ts">
    import { ref, onMounted, computed } from "vue";
    import { ElMessage } from "element-plus";
    import { useRoute, useRouter } from "vue-router";
    import { postV3LevelUpdate, postV3LevelWait } from "@/assets/api";
    import { _mallStore } from "@/store/config";
    import { storeToRefs } from "pinia";
    import { memberLevelsHandler } from "@/views/SystemSettings/MarketingRule/MemberLevelList/handler";

    import AddLevel from "@/views/SystemSettings/MarketingRule/MemberLevelList/components/AddLevel.vue";
    import HighLevel from "@/views/SystemSettings/MarketingRule/MemberLevelList/components/HighLevel.vue";

    const { isGroupManagementPage } = storeToRefs(_mallStore);
    const route = useRoute();
    const router = useRouter();

    let isEdit = ref<boolean>(false);
    let showPageBtn = ref<boolean>(false);
    onMounted(() => {
        getTableList();
    })

    // 列表请求 loading
    const getListLoading = () => {
        tableLoading.value = true;
        getTableList();
    }

    let emptyText = ref<string>('');
    let tableLoading = ref<boolean>(false);
    let tableData = ref<ObjValueAny[]>([]);
    let total = ref<number>(0);
    let isUpdate = ref<boolean>(false);
    // 会员等级列表
    const getTableList = () => {
        emptyText.value = '加载中...';
        const params: ObjValueAny = {};
        params.company_id = _mallStore.companyId;
        // 如果是商场
        if (!isGroupManagementPage.value) {
            params.mall_id = _mallStore.mallId;
        }
        postV3LevelWait(params, { noRepeat: 1 }).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                isUpdate.value = resp.data.is_update;
                const data: ObjValueAny[] = resp.data?.levels || [];
                for (let i = 0; i < data.length; i++) {
                    memberLevelsHandler(data[i], i);
                }
                tableData.value = data;
                total.value = resp.meta?.total || 0;
                showDeleteBtnHandler();
            } else {
                ElMessage.error(resp.msg);
            }
            emptyText.value = '暂无数据';
            tableLoading.value = false;
            showPageBtn.value = true;
        })
    }
    // 显示删除按钮
    let noSpecialLevelsIndex = ref<number>(-1);
    const showDeleteBtnHandler = () => {
        for (let i = 0; i < tableData.value.length; i++) {
            if (+tableData.value[i].is_special !== 1) {
                noSpecialLevelsIndex.value = i;
            }
        }
        for (let i = 0; i < tableData.value.length; i++) {
            tableData.value[i].showDelete = +tableData.value[i].is_special === 1 || i === noSpecialLevelsIndex.value;
        }
    }
    // 删除 会员等级
    const removeLevels = (i: number) => {
        const removeData: ObjValueAny = tableData.value[i];
        ElMessage.closeAll();
        for (let row of tableData.value) {
            if ((row.id === removeData.level_id || row.id === removeData.id) && +row.is_link_member === 1) {
                ElMessage.error('该等级下存在会员，不可删除');
                return;
            }
        }
        tableData.value.splice(i, 1);
        showDeleteBtnHandler();
    }

    const onEdit = () => {
        isEdit.value = true;
    }
    const closeEdit = () => {
        isEdit.value = false;
    }

    let memberDetail = ref<ObjValueAny>({});
    let addLevelDialog = ref<boolean>(false);
    const isSpecial = computed(() => {
        return memberDetail.value.is_special === 1;
    })
    // 显示 新增/编辑 会员等级弹窗
    const showAddLevelDialog = () => {
        addLevelDialog.value = true;
    }
    // 新增 普通等级
    const addOrdinaryLevel = () => {
        const _ordinaryLevels: ObjValueAny[] = tableData.value.filter((row: ObjValueAny) => +row.is_special !== 1);
        memberDetail.value = { index: _ordinaryLevels.length, is_special: 0 };
        showAddLevelDialog();
    }
    // 新增 特殊等级
    const addSpecialLevel = () => {
        memberDetail.value = { is_special: 1 };
        showAddLevelDialog();
    }
    // 编辑 会员等级
    const editLevel = (row: ObjValueAny, i: number) => {
        row.index = i;
        row.edit = true;
        memberDetail.value = row;
        showAddLevelDialog();
    }

    const addLevelValue = (row: ObjValueAny = {}) => {
        const _index: number = memberDetail.value.index;
        row.is_special = memberDetail.value.is_special;
        if (memberDetail.value.edit) {
            tableData.value[_index] = Object.assign({}, tableData.value[_index], row);
        } else {
            if (isSpecial.value) {
                // 新增 特殊等级
                tableData.value.push(row);
            } else {
                // 新增 普通等级
                tableData.value.splice(_index, 0, row);
            }
        }
        for (let i = 0; i < tableData.value.length; i++) {
            memberLevelsHandler(tableData.value[i], i);
        }
        console.info('row', row);
        showDeleteBtnHandler();
    }

    const onLevelUpdate = () => {
        const _query: ObjValueAny[] = JSON.parse(JSON.stringify(tableData.value));
        for (let row of _query) {
            if (row.hasOwnProperty('index')) delete row.index;
            if (row.hasOwnProperty('edit')) delete row.edit;
            if (row.gifts?.length) {
                if (typeof row.gifts[0] !== 'number') {
                    row.gifts = row.gifts.map((ele: ObjValueAny) => ele.id);
                }
            }
        }
        postV3LevelUpdate({
            company_id: _mallStore.companyId,
            mall_id: _mallStore.mallId,
            data: _query,
        }).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                getListLoading();
            } else {
                ElMessage.error(resp.msg);
            }
        })
    }

    // const query: ObjValueAny = JSON.parse(JSON.stringify(ruleForm));
    // if (query.year_day_periods?.length) {
    //     query.year_day_periods = {
    //         start_day: query.year_day_periods[0],
    //         end_day: query.year_day_periods[1],
    //     };
    // } else {
    //     query.year_day_periods = {};
    // }
    // if (query.customize_time_periods?.length) {
    //     query.customize_time_periods = {
    //         start_day: query.customize_time_periods[0],
    //         end_day: query.customize_time_periods[1],
    //     };
    // } else {
    //     query.customize_time_periods = {};
    // }

    const routerLevelUpdate = () => {
        router.push('/memberLevelUpdate');
    }

    let highLevelDialog = ref<boolean>(false);
    const showHighLevel = () => {
        highLevelDialog.value = true;
    }
</script>

<style scoped lang="scss"></style>